import React, {Component} from "react";
import {
  Table,
  Badge,
  Card,
  Input,
  Select,
  message,
  Modal,
  Tree,
  Button,
  Icon,
  Tooltip
} from 'antd';
import {connect} from "dva";
import SearchForm from '../../components/AutoForm/SearchForm';
import EditForm from '../../components/AutoForm/EditForm';
const {Option} = Select;
const confirm = Modal.confirm;
const { TreeNode } = Tree;
const statusMap = ['processing', 'warning'];
const status = ['使用中', '锁定'];
const renderTreeNodes = data =>
  data.map(item => {
    if (item.children) {
      return (
        <TreeNode title={item.title} key={item.key} dataRef={item}>
          {renderTreeNodes(item.children)}
        </TreeNode>
      );
    }
    return <TreeNode {...item} />;
  });

@connect(({role, company, loading}) => ({
  tableLoading: loading.effects['role/page'],
  modalInsertLoading: loading.effects['role/insert'],
  modalUpdateLoading: loading.effects['role/update'],
  modalTreeLoading: loading.effects['role/roleResSave'],
  searchForm: role.searchForm,
  modalForm: role.modalForm,
  addForm: role.addForm,
  modalVisible: role.modalVisible,
  tableData: role.list,
  selection: role.selection,
  pagination: role.pagination,
  optFlag: role.optFlag,
  compOptions: company.compOptions,
  treeModalTitle: role.treeModalTitle,
  treeModalVisible: role.treeModalVisible,
  treeData: role.treeData,
  treeSelectKeys: role.treeSelectKeys,
  activeRoleId: role.activeRoleId,
  treeSubmitData: role.treeSubmitData
}))
export default class List extends Component {

  columns = [
    {
      key: 1,
      title: '序号',
      width: "50px",
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
    },
    {
      title: '公司编码',
      dataIndex: 'compCode',
    },
    {
      title: '锁定/使用',
      width: "120px",
      dataIndex: 'isLock',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    },
    {
      title: '操作',
      render: (text, record, index) => {
        return (
          <div>
            <Tooltip title="资源分配"><Button onClick={() => {this.handleResourcesTree(text, record, index)}}
                                          shape="circle" size="small"><Icon type="appstore"/></Button></Tooltip>
          </div>
        )
      },
    }
  ];
  componentDidMount() {
    const {dispatch, pagination} = this.props;
    dispatch({
      type: 'role/page',
      payload: pagination
    });
    dispatch({
      type: 'company/getCompOptions'
    });
  }

  handleSearch = (page) => {
    const {dispatch, pagination, searchForm} = this.props;
    let pageParam = {pageSize: pagination.pageSize, current: pagination.current}
    if (page) {
      pageParam = {pageSize: page.pageSize, current: page.current}
    }
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const param = {
      ...searchValue,
      ...pageParam
    };
    dispatch({
      type: 'role/page',
      payload: param
    })
  }

  handleSearchChange = (fields) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'role/handleSearchChange',
      payload: fields
    })
  }

  handleModalVisible = (opt) => {
    const {dispatch, modalVisible,  selection, addForm} = this.props;
    let payload = {modalVisible: !modalVisible};
    let modalForm = {};
    if ('edit' === opt) {
      if (JSON.stringify(selection) === '{}') {
        message.error('请选择一条记录');
        return;
      } else {
        Object.keys(selection).map((key) => {
          modalForm[key] = {value: selection[key]}
        })
      }
    } else if ("add" === opt) {
      Object.keys(addForm).map((key) => {
        modalForm[key] = {value: addForm[key]}
      })
    }

    if (!modalVisible) {
      payload.optFlag = opt;
      payload.modalForm = modalForm;
    }
    dispatch({
      type: 'role/handleModalVisible',
      payload: payload
    })
  }

  handleModalChange = (fields) => {
    const {dispatch, optFlag, addForm} = this.props;
    const payload = {fields: fields, optFlag: optFlag, addForm: addForm};
    dispatch({
      type: 'role/handleModalChange',
      payload: payload
    })
  }

  handleTableChange = (pagination) => {
    this.handleSearch(pagination);
  }

  handleOk = (fields) => {

    const {dispatch, optFlag, searchForm, pagination} = this.props;
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const payload = {
      fields: fields,
      searchForm: searchValue,
      pagination: pagination
    }
    if (optFlag === 'add') {
      dispatch({
        type: 'role/insert',
        payload: payload
      })
    } else if (optFlag === 'edit') {
      dispatch({
        type: 'role/update',
        payload: payload
      })
    }

  }

  onSelect = (record)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'role/handleTableSelection',
      payload: record
    })
  };

  handleDel = () => {
    const {dispatch, selection, searchForm, pagination } = this.props;
    if (JSON.stringify(selection) === '{}') {
      message.error('请选择一条记录');
      return;
    }
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const payload = {
      fields: selection,
      searchForm: searchValue,
      pagination: pagination
    }
    confirm({
      title: '是否确认删除此角色?',
      content: `编码：${selection.roleCode}; 名称：${selection.roleName}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'role/del',
          payload: payload,
        });
      },
    });
  }

  handleTreeVisible = () => {
    const {dispatch,treeModalVisible} = this.props;
    dispatch({
      type: 'role/handleTreeVisible',
      payload: !treeModalVisible
    })
  }

  handleResourcesTree = (text, record, index) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'role/getTreeData',
      payload: {roleId: record.id, compCode: record.compCode}
    }).then(() => {
      this.handleTreeVisible();
    })
    dispatch({
      type: 'role/handleTreeTitleChange',
      payload: `分配资源(编码：${record.roleCode}，名称：${record.roleName})`
    })
    dispatch({
      type: 'role/handleActiveRoleChange',
      payload: record.id
    })
  }

  treeOnCheck = (checkedKeys,e) =>{
    const keys = checkedKeys.concat(e.halfCheckedKeys);
    const {dispatch} = this.props;
    dispatch({
      type: 'role/handleSelectKeys',
      payload: checkedKeys
    });
    dispatch({
      type: 'role/handleTreeSubmitData',
      payload: keys
    });
  }
  render() {
    const {
      pagination,
      tableLoading,
      modalInsertLoading,
      modalUpdateLoading,
      modalTreeLoading,
      tableData,
      modalVisible,
      modalForm,
      searchForm,
      optFlag,
      compOptions,
      treeModalTitle,
      treeModalVisible,
      treeData,
      treeSelectKeys
    } = this.props;
    const options = compOptions.map(d => <Option key={d.value} value={d.value}>{d.label}</Option>);
    const fields = [
      {
        cols: [
          {
            md: 6,
            label: '名称',
            name: 'roleName',
            component: <Input placeholder="请输入"/>
          },
          {
            md: 6,
            label: '编码',
            name: 'roleCode',
            component: <Input placeholder="请输入"/>
          },
          {
            md: 6,
            label: '所属公司',
            name: 'compCode',
            component: <Select>{options}</Select>
          },
          {
            md: 6,
            label: '使用状态',
            name: 'isLock',
            component: <Select placeholder="请选择" style={{width: '100%'}}>
              <Option value="0">使用中</Option>
              <Option value="1">锁定</Option>
            </Select>
          }
        ]
      }
    ]
    const EditRows = [
      {
        cols: [
          {
            label: '名称',
            name: 'roleName',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input placeholder="请输入名称"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '编码',
            name: 'roleCode',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input disabled={optFlag === 'add' ? false : true} placeholder="请输入编码"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '公司编码',
            name: 'compCode',
            md: 18,
            rules: [{required: true, message: '请选择公司！'}],
            component: <Select>{options}</Select>
          },
          {
            name: 'id',
            component: <Input type="hidden"/>
          }
        ]
      },
    ]

    const showTotal = (total) => {
      return `总记录： ${total} 条`;
    }
    pagination.showTotal = showTotal;
    const rowSelection = {
      type: "radio",
      onSelect: this.onSelect
    };

    return (
      <Card bodyStyle={{padding: 0}}>
        <SearchForm
          header="系统角色->操作"
          layout="inline"
          fields={fields}
          fieldValue={searchForm}
          onSubmit={this.handleSearch}
          onModal={this.handleModalVisible}
          onFieldsChange={this.handleSearchChange}
          onDel={this.handleDel}
        />
        <Table
          pagination={pagination}
          columns={this.columns}
          loading={tableLoading}
          dataSource={tableData}
          rowSelection={rowSelection}
          rowKey={record => record.id}
          scroll={{x: 'max-content'}}
          size="small"
          onChange={this.handleTableChange}
          bordered
        />

        <EditForm
          rows={EditRows}
          fieldValue={modalForm}
          onFieldsChange={this.handleModalChange}
          optFlag={optFlag}
          visible={modalVisible}
          onOk={this.handleOk}
          onCancel={this.handleModalVisible}
          confirmLoading={modalInsertLoading || modalUpdateLoading}
        />

        <Modal
          visible={treeModalVisible}
          title={treeModalTitle}
          okText="确定"
          cancelText="取消"
          onCancel={this.handleTreeVisible}
          onOk={this.handleTreeOk}
          confirmLoading={modalTreeLoading}
        >
          <Tree
            checkable
            showLine
            checkedKeys={treeSelectKeys}
            onCheck={this.treeOnCheck}
            defaultExpandAll
          >
            {renderTreeNodes(treeData)}
          </Tree>
        </Modal>
      </Card>
    )
  }
}
